package roboGP;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.Semaphore;

import robocode.BattleResults;
import robocode.control.BattleSpecification;
import robocode.control.BattlefieldSpecification;
import robocode.control.RobocodeEngine;
import robocode.control.RobotSpecification;

public class BattleRunnerSlave extends UnicastRemoteObject implements IBattleRunnerSlave 
{
	private static final long serialVersionUID = 3737946744242513784L;
	private RobocodeEngine _engine;
	private BattlefieldSpecification _battlefield;
	private BattleObserver _battleObserver;
	private BattleResults[] _results = null; 
	private Semaphore _semaphore;

	public static void main(String[] args) 
			throws RemoteException, MalformedURLException
	{
		BattleRunnerSlave arena = new BattleRunnerSlave();
		Naming.rebind("//localhost/BattleRunnerSlave" + args[0], arena);
		System.out.println("BattleRunnerSlave" + args[0] + " attivato.");
	}
	
	public BattleRunnerSlave() throws RemoteException
	{
		super();
		_engine = new RobocodeEngine(new java.io.File("robocode"));
		_battleObserver = new BattleObserver();
		_engine.addBattleListener(_battleObserver);
		_engine.setVisible(false);
		_battlefield = new BattlefieldSpecification(800, 600);
		_semaphore = new Semaphore(1);
	}
	
	public void runBattle(RobotSpecification[] selectedBots, int rounds)
			throws RemoteException 
	{
		try 
		{
			_semaphore.acquire();
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		BattleSpecification battleSpec = new BattleSpecification(rounds, _battlefield, selectedBots);
		_engine.runBattle(battleSpec, true);
		_results = _battleObserver.getResults();
		_semaphore.release();
		
	}

	public BattleResults[] getResults() throws RemoteException 
	{
		try 
		{
			_semaphore.acquire();
			_semaphore.release();
		} 
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		
		return _results;
	}

}
